/**
 * http://www.koorz.com
 * Copyright (c) 2012 shanghai meiku information technology co,.ltd
 */
package com.koorz.oauth.services;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Page;
import com.koorz.constant.GlobalConstant;
import com.koorz.modules.commission.CommissionRate;
import com.koorz.modules.user.PartyAccount;
import com.koorz.modules.user.User;
import com.koorz.oauth.model.OAuthConstants;
import com.koorz.oauth.model.OAuthRequest;
import com.koorz.oauth.model.Response;
import com.koorz.oauth.model.Token;
import com.koorz.oauth.model.UserWrapper;
import com.koorz.oauth.model.Verb;
import com.koorz.oauth.model.weibo.WeiboToken;
import com.koorz.utils.DateUtil;
import com.koorz.utils.FileUtil;
import com.koorz.utils.IdManage;
import com.koorz.utils.LoginUtil.WeiboType;

/**
 * 功能描述：
 * 作        者：尹东东 
 * 创建时间：2013-4-8 下午5:22:29
 * 版  本  号：1.0
 */
public class WeiboService extends ApiService{
	private String API_URL_PREFIX = "https://api.weibo.com/2";
	private String USER_PREFIX = API_URL_PREFIX + "/users";
	private String STATUSES_PREFIX = API_URL_PREFIX + "/statuses";
	private String FRIENDSHIPS_PREFIX = API_URL_PREFIX + "/friendships";
	
	@SuppressWarnings("rawtypes")
	@Override
	public User bindUser(Token objClass) {
		WeiboToken accessToken = (WeiboToken) objClass;
		User user  = null;
		UserWrapper userWrapper = getUserInfo(accessToken.getUid(), accessToken.getAccessToken());
		user = User.dao.findFirst("select u.* from user as u inner join party_account as pa on pa.user_id=u.id where pa.account_id=?",userWrapper.getUid());	
		if (user == null) {
			user = new User();
			String userId = IdManage.nextId(IdManage.USER);
			user.set("id", userId);
			user.set("nickname",userWrapper.getNickname());
			user.set("gender", userWrapper.getGender());
			user.set("signature", userWrapper.getDesc());
			String tmp = FileUtil.saveAvatar(userWrapper.getAvatarLarge(), userId);
			if(StringUtils.isEmpty(tmp)){
				user.set("avatar", GlobalConstant.DEFAULT_AVATAR);
				user.set("avatar_large", GlobalConstant.DEFAULT_AVATAR_LARGE);
			}else {
				JSONObject avatarJson = JSON.parseObject(tmp);
				user.set("avatar", avatarJson.getString("avatar"));
				user.set("avatar_large", avatarJson.getString("avatarLarge"));
			}
			user.set("create_time", DateUtil.getNowDateTime());
			user.set("score", 0);
			user.set("online", 1);
			CommissionRate rate = CommissionRate.dao.findFirst("select * from commission_rate where type=?", CommissionRate.Type.DEFAULT.ordinal());
			user.set("account_balance", 0.0);
			user.set("commission_rate", rate.getDouble("commission_rate"));
			user.set("type", User.UserType.SELF.ordinal());
			user.set("freeze", User.IsFreeze.UNFREEZE.ordinal());
			user.set("role_id", User.DEFAULT_ROLE);
			user.save();
			
			PartyAccount account = new PartyAccount();
			account.set("id", IdManage.nextId(IdManage.PARTYACCOUNT));
			account.set("user_id", userId);
			account.set("account_id", userWrapper.getUid());
			account.set("access_token", accessToken.getAccessToken());
			account.set("refresh_token", "");
			account.set("expires_in", accessToken.getExpiresIn());
			account.set("type", WeiboType.SINA.ordinal());
			account.save();
			
			user.put("platform",WeiboType.SINA.ordinal());
		} else {
			user.set("nickname", userWrapper.getNickname());
			user.set("gender", userWrapper.getGender());
			user.set("signature", userWrapper.getDesc());
			user.set("online", 1);
			String tmp = FileUtil.saveAvatar(userWrapper.getAvatarLarge(), user.getStr("id"));
			if(StringUtils.isEmpty(tmp)){
				user.set("avatar", GlobalConstant.DEFAULT_AVATAR);
				user.set("avatar_large", GlobalConstant.DEFAULT_AVATAR_LARGE);
			}else {
				JSONObject avatarJson = JSON.parseObject(tmp);
				user.set("avatar", avatarJson.getString("avatar"));
				user.set("avatar_large", avatarJson.getString("avatarLarge"));
			}
			user.update();
			
			PartyAccount account = PartyAccount.dao.findFirst("select id,user_id,access_token,expires_in from party_account where user_id=? and account_id=?", 
					new Object[]{user.getStr("id"),userWrapper.getUid()});
			account.set("access_token", accessToken.getAccessToken());
			account.set("expires_in", accessToken.getExpiresIn());
			account.update();
			
			user.put("platform",WeiboType.SINA.ordinal());
		}
		return user;
	}
	
	/**
	 * 
	 * 功能描述：获取当前登录用户信息
	 * 作        者：尹东东
	 * 创建时间：2013-4-9 上午12:10:10
	 * 参       数：
	 * 返       回:无
	 * 异       常：无
	 * 版  本 号：1.0
	 */
	public UserWrapper getUserInfo(String uid,String accessToken){
		OAuthRequest request = createRequest(Verb.GET, USER_PREFIX+"/show.json");
		request.addQuerystringParameter("uid", uid);
		request.addQuerystringParameter(OAuthConstants.ACCESS_TOKEN,accessToken);
	    Response response = request.send();
	    if(response.isSuccessful()){
	    	JSONObject json = JSON.parseObject(response.getBody());
	    	return wapperUser(json);
	    }
	    return null;
	}
	
	/**
	 * 
	 * 功能描述：获取好友列表
	 * 作        者：尹东东
	 * 创建时间：2013-4-9 上午1:20:34
	 * 参       数：
	 * 返       回:无
	 * 异       常：无
	 * 版  本 号：1.0
	 */
	public Page<UserWrapper> getUserFollowers(String accessToken,
			String uid,int page, int count) {
		OAuthRequest request = createRequest(Verb.GET, FRIENDSHIPS_PREFIX+"/followers.json");
		request.addQuerystringParameter("uid", uid);
		request.addQuerystringParameter("count", count+"");
		request.addQuerystringParameter("cursor",(page-1)*count+"");
		request.addQuerystringParameter(OAuthConstants.ACCESS_TOKEN,accessToken);
	    Response response = request.send();
	    if(response.isSuccessful()){
	    	JSONObject json = JSON.parseObject(response.getBody());
			JSONArray usersJson = json.getJSONArray("users");
			if(usersJson.size() > 0){
				return new Page<UserWrapper>(wapperUsers(usersJson),page,count,page,count);
			}
	    }
	    return new Page<UserWrapper>(new ArrayList<UserWrapper>(0),page,count,0,0);
	}
	
	/**
	 * 
	 * 功能描述：邀请好友
	 * 作        者：尹东东
	 * 创建时间：2013-4-9 上午1:20:50
	 * 参       数：
	 * 返       回:无
	 * 异       常：无
	 * 版  本 号：1.0
	 */
	public int inviteFriend(String accessToken,String status,String atUser) {
		String inviteFriendTemplate = "我正在用%s。%s @%s";
		OAuthRequest request = createRequest(Verb.POST, STATUSES_PREFIX+"/update.json");
		request.addQuerystringParameter("status", String.format(inviteFriendTemplate,GlobalConstant.DOMAIN_HOST,status,atUser));
		request.addQuerystringParameter(OAuthConstants.ACCESS_TOKEN,accessToken);
	    Response response = request.send();
	    if(response.isSuccessful()){
	    	return 1;
	    }
	    return 0;
	}
	
	/**
	 * 
	 * 功能描述：分享微博
	 * 作        者：尹东东
	 * 创建时间：2013-4-9 上午1:22:46
	 * 参       数：
	 * 返       回:无
	 * 异       常：无
	 * 版  本 号：1.0
	 */
	public int shareStatus(String accessToken, String status) {
		//String shareTemplate = "分享  %s 的歌曲 ♫%s:%s %s （分享自 @米蕊网）";
		OAuthRequest request = createRequest(Verb.POST, STATUSES_PREFIX+"/update.json");
		//String url = GlobalConstant.DOMAIN_HOST+"/"+uid;
		request.addQuerystringParameter("status", status);
		request.addQuerystringParameter(OAuthConstants.ACCESS_TOKEN,accessToken);
	    Response response = request.send();
	    if(response.isSuccessful()){
	    	return 1;
	    }
	    return 0;
	}

	@Override
	protected UserWrapper wapperUser(JSONObject obj) {
		UserWrapper user = new UserWrapper();
    	user.setAvatar(obj.getString("profile_image_url"));
    	user.setAvatarLarge(obj.getString("avatar_large"));
    	user.setDesc(obj.getString("description"));
    	//m--男，f--女,n--未知
    	if("m".equals(obj.getString("gender"))){
    		user.setGender(1);
    	}else if("f".equals(obj.getString("gender"))){
    		user.setGender(0);
    	}else {
    		user.setGender(2);
    	}
    	user.setLoc(obj.getString("location"));
    	user.setNickname(obj.getString("screen_name"));
    	user.setUid(obj.getString("id"));
		return user;
	}

	@Override
	protected List<UserWrapper> wapperUsers(JSONArray array) {
		 List<UserWrapper> users = new ArrayList<UserWrapper>();
		 for(int i=0;i<array.size();i++){
			 JSONObject userObj = array.getJSONObject(i);
			 users.add(wapperUser(userObj));
		 }
		 return users;
	}
}
